package info.jimao.newsdk.utilities;

import android.annotation.SuppressLint;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日期时间反序列化，处理时区，在GSON中使用，<br>
 * 将JSON时间字符串(形如 "/Date(1347451260000+0800)/")转换成java.util.Date对象
 */
public class TimeZoneDateDeserializer implements JsonDeserializer<Date> {

    @SuppressLint("UseValueOf")
    public Date deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        Pattern pattern = Pattern.compile("\\/(Date\\((.*?)(\\+.*)?\\))\\/");
        Matcher matcher = pattern.matcher(arg0.getAsJsonPrimitive().getAsString());
        String million = matcher.replaceAll("$2");

        /**
         * TODO 时区处理
         */
        String timeZone = matcher.replaceAll("$3");
        Long timeZoneMillion = 0L;
        if (!("null").equals(timeZone)) {
            timeZoneMillion = new Long(timeZone.substring(1)) * 36 * 1000;

            if ("-".equals(timeZone.substring(0, 1))) {
                timeZoneMillion = -timeZoneMillion;
            }
        }

        return new Date(new Long(million) + timeZoneMillion);
    }
}
